<template>
  <div class="promoForm">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="160px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="开团时间" prop="startTime">
            <el-date-picker
              v-model="startTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="09:00:00">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="endTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="17:00:00">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    
      <el-row>
        <el-col :span="10">
          <el-form-item label="前端是否显示">
            <el-radio v-model="ruleForm.isShow" :label=0>否</el-radio>
            <el-radio v-model="ruleForm.isShow" :label=1>是</el-radio>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="20">
          <el-form-item label="公告" prop="notice">
            <el-input v-model="ruleForm.notice"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">修 改/提 交</el-button>
        <el-button @click="goBack">返 回</el-button>
      </el-form-item>
    </el-form>

    <div class="split"></div>
    <div class="pick-manager">
      <span>选择开团团长</span>
      <el-button type="primary" @click="pickManager()">选择开团团长</el-button>
    </div>

    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="name" label="姓名" align="center"></el-table-column>
      <el-table-column prop="address" label="地址" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="rewardMoney" label="已获佣金" align="center"></el-table-column>
      <el-table-column prop="frozenMoney" label="冻结佣金" align="center"></el-table-column>
      <el-table-column prop="nobalanceMoney" label="未结算佣金" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center" :formatter="statusFormat"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleRemove(scope.$index, scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

     <div class="split"></div>
    <div class="pick-manager">
      <span>选择开团商品</span>
      <el-button type="primary" @click="pickProduct()">选择开团商品</el-button>
    </div>

    <el-table :data="productList" stripe style="width: 100%">
      <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
      <el-table-column prop="originPrice" label="原价" align="center"></el-table-column>
      <el-table-column prop="presentPrice" label="现价" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleRemove2(scope.$index, scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="bottom-opt">
      <el-button type="primary" @click="handleSubmit">修 改/提 交</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>

    <managerModal @select="selectItem" ref="managerModal" :list="managerModalList"></managerModal>
    <productModal @select="selectItem2" ref="productModal" :list="productModalList"></productModal>
  </div>
</template>

<script>
import api from "@/api/promo";
import managerModal from "./managerModal";
import productModal from "./productModal";
import productAPI from "@/api/product";
import managerAPI from "@/api/manager";

const SUCCESS = 0;
export default {
  components: {
    managerModal,
    productModal
  },
  data() {
    return {
      tableData: [],
      ruleForm: {
        id: null,
        startTimestamp: "",
        endTimestamp: "",
        isShow: 0,
        notice: "",
        promoManagerList: [],
        promoProductList: []
      },
      rules: {
        notice: [{ required: true, message: "请填写公告", trigger: "change" }]
      },
      startTime: "",
      endTime: "",
      productList: [],
      productModalList: [],
      managerModalList: []
    };
  },
  created() {
    let id = this.$route.query.id;
    if (id) {
      this.ruleForm.id = id;
      this._getDetail();
    }
  },
  methods: {
    handleRemove(index, rows) {
      this.tableData.splice(index, 1);
    },
    handleRemove2(index, rows) {
      this.productList.splice(index, 1);
    },
    statusFormat(row, column) {
      let status = row[column.property];
      if (status == 0) {
        return "正常";
      } else {
        return "冻结";
      }
    },
    pickManager() {
      managerAPI.getAllNormal().then(response => {
        this.managerModalList = response.data.managerList;
      });
      this.$refs.managerModal.show = true;
    },
    pickProduct() {
      if (this.productModalList.length == 0) {
        this._getPromoProductList();
      }
      this.$refs.productModal.show = true;
    },
    _getPromoProductList() {
      productAPI.getAllNormal().then(response => {
        this.productModalList = response.data.productList;
        //遍历赋值....
        //....
        // this.$set(item, "selected", false);

        this.productModalList.forEach(item => {
          this.$set(item, "selected", false);
        });

        this.productList.forEach(selectedProduct => {
          this.productModalList.forEach(item => {
            if (selectedProduct.productId == item.id) {
              item.selected = true;
            }
          });
        });
      });
    },
    selectItem(selectedList) {
      this.tableData = selectedList;
      this.$refs.managerModal.show = false;
    },
    selectItem2(selectedList) {
      this.productList = selectedList;
      this.$refs.productModal.show = false;
    },
    _getDetail() {
      api.getDetail(this.ruleForm.id).then(response => {
        if (response.code == SUCCESS) {
          this.ruleForm = response.data.promo;
          this.startTime = new Date(this.ruleForm.startTimestamp);
          this.endTime = new Date(this.ruleForm.endTimestamp);

          this.tableData = response.data.managerList;

          this.productList = response.data.productList;
        }
      });
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          //判断开始时间和结束时间是否已选
          if (!this.startTime) {
            this.$message({
              type: "warning",
              message: "请选择开始时间"
            });
            return;
          }

          if (!this.endTime) {
            this.$message({
              type: "warning",
              message: "请选择结束时间"
            });
            return;
          }

          //判断开团团长和开团商品是否已选
          if (!this.tableData.length) {
            this.$message({
              type: "warning",
              message: "请选择开团团长"
            });
            return;
          }

          if (!this.productList.length) {
            this.$message({
              type: "warning",
              message: "请选择开团商品"
            });
            return;
          }

          //处理时间格式,转换成时间戳给数据库保存
          this.ruleForm.startTimestamp = new Date(this.startTime).getTime();
          this.ruleForm.endTimestamp = new Date(this.endTime).getTime();

          this.ruleForm.promoManagerList = [];
          this.ruleForm.promoProductList = [];
          this.tableData.forEach(manager => {
            let promoManager = {
              managerId: manager.id
            };
            this.ruleForm.promoManagerList.push(promoManager);
          });

          this.productList.forEach(product => {
            let promoProduct = {};
            if (product.productId) {
              Object.assign(promoProduct, { productId: product.productId });
            } else {
              Object.assign(promoProduct, { productId: product.id });
            }
            this.ruleForm.promoProductList.push(promoProduct);
          });

          if (this.ruleForm.id) {
            this._updateObj();
          } else {
            this._addObj();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    _addObj() {
      api.add(this.ruleForm).then(response => {
        if (response.code == SUCCESS) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "/promo/list" });
        } else {
          this.$message({
            type: "warning",
            message: response.message
          });
        }
      });
    },
    _updateObj() {
      api.update(this.ruleForm).then(response => {
        if (response.code == SUCCESS) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "/promo/list" });
        } else {
          this.$message({
            type: "warning",
            message: response.message
          });
        }
      });
    },
    goBack() {
      this.$router.back();
    }
  }
};
</script>


<style lang="less">
.promoForm {
  .split {
    border-top: 1px dashed #999;
    margin: 20px 0;
  }

  .pick-manager {
    margin: 50px 0;
    padding-left: 50px;
    span {
      vertical-align: middle;
    }
  }

  button {
    padding-left: 50px !important;
    padding-right: 50px !important;
  }

  .bottom-opt {
    padding-left: 160px;
    margin-top: 50px;
  }
}
</style>